package com.chidopi.market.aa.actions;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.chidopi.cdf.exception.CdfException;
import com.chidopi.cdf.service.IBaseService;
import com.chidopi.cdf.service.ICommonService;
import com.chidopi.cdf.struts1actions.StandardOperatorAction;
import com.chidopi.cdf.util.ModelContextFactory;
import com.chidopi.market.aa.domain.Accounts;
import com.chidopi.market.aa.domain.Functions;
import com.chidopi.market.aa.domain.Role2FunctionItem;
import com.chidopi.market.aa.domain.Roles;
import com.chidopi.market.util.MessageHandler;

public class RoleAction extends StandardOperatorAction<Roles> {
	private ICommonService commonService;
	private IBaseService<Accounts> accountService;
	private IBaseService<Functions> functionService;
//	private IBaseService<FunctionItems> itemService;

	public RoleAction(){
		this("");
	}
	
	@SuppressWarnings("unchecked")
	public RoleAction(String entryURL) {
		this.entryURL = entryURL;
		try {
			this.baseService = (IBaseService<Roles>)
				ModelContextFactory.get("roleService", IBaseService.class);
			this.commonService = ModelContextFactory.getT("commonService", ICommonService.class);
			this.accountService = (IBaseService<Accounts>)
				ModelContextFactory.get("accountService", IBaseService.class);
			this.functionService = (IBaseService<Functions>)
				ModelContextFactory.get("functionService", IBaseService.class);
//			this.itemService = (IBaseService<FunctionItems>)
//				ModelContextFactory.get("itemService", IBaseService.class);
		} catch (Exception e) {
			this.baseService = null;
			logger.warn("initial", e);
		}
	}

	private static final String[] conditions =
		{"id", "rolename", "enable_flag"};
	public ActionForward query(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (null == this.baseService) return mapping.findForward("error");
		StringBuffer sql = new StringBuffer();
		for (String cond : conditions) {
			String value = request.getParameter(cond);
			//String value = (String) dynaForm.get(cond);
			logger.debug(cond + "=" + value);
			if (value == null || value.trim().equals("")) continue;
			if (cond.equals("enable_flag")) {
				String disable_flag = request.getParameter("disable_flag");
				//String disable_flag = (String) dynaForm.get("disable_flag");
				if (disable_flag != null) continue;
			}
			if (sql.length() > 1) sql.append("and ");
			if (cond.endsWith("_flag")) {
				sql.append("enable_flag = '" + value + "' ");
			} else {
				sql.append(cond + " like '%" + value + "%' ");
			}
		}
		logger.debug("sql=" + sql.toString());
		List<Roles> list = this.baseService.find(sql.toString());
		logger.debug("size=" + list.size());
		JSONArray json = JSONArray.fromObject(list);

		PrintWriter out=response.getWriter();
		logger.debug(json.toString());
        out.println(json);
        out.flush();
		return null;
	}

	@Override
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		logger.debug("local op=" + request.getParameter("op"));
		logger.debug("local id=" + request.getParameter("id"));
		return super.update(mapping, form, request, response);
	}

//	@Override
//	public Roles newValueObject() {
//		return new Roles();
//	}

	/**
	 * query function item by role_id and function_id
	 */
	public ActionForward queryFunctionItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String function_id = request.getParameter("function_id");
		String role_id = request.getParameter("role_id");
		logger.debug("function_id=" + function_id + "&role_id=" + role_id);

		String sql = "select a.id, a.itemname, b.visable, b.enable from functionitems a, role2functionitem b where a.id=b.item_id ";
		sql += "and b.role_id=? ";
		List<Map<String, Object>> functionItems = null;
		if (null != function_id) {
			sql += "and a.function_id=? ";
			functionItems = this.commonService.queryForList(sql, role_id, function_id);
		} else {
			sql += "order by a.function_id, a.id ";
			functionItems = this.commonService.queryForList(sql, role_id);
		}
		if (null != functionItems && functionItems.size() > 0) {
			JSONArray json = JSONArray.fromObject(functionItems);

			PrintWriter out=response.getWriter();
			logger.debug(json.toString());
	        out.println(json);
		} else {
			logger.info(function_id + " disable or not exists");
			PrintWriter out=response.getWriter();
			out.println("[]");
		}
		return null;
	}

	public ActionForward setAccount2Role(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		request.setAttribute("role_id", role_id);
		return mapping.findForward("success");
	}

	public ActionForward queryAccount(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		List<Accounts> accounts = this.accountService.find("id not in (select account_id from account2role where role_id=?) ", role_id);
		JSONArray json = JSONArray.fromObject(accounts);
		PrintWriter out=response.getWriter();
		logger.debug("queryAccount=" + json.toString());
        out.println(json);
		return null;
	}

	public ActionForward queryAccountSelected(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		List<Accounts> accounts = this.accountService.find("id in (select account_id from account2role where role_id=?) ", role_id);
		JSONArray json = JSONArray.fromObject(accounts);
		PrintWriter out=response.getWriter();
		logger.debug("queryAccountSelected=" + json.toString());
        out.println(json);
		return null;
	}

	public ActionForward setRole2Account(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		request.setAttribute("role_id", role_id);
		return mapping.findForward("success");
	}

	public ActionForward queryFunction(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		List<Functions> functions = this.functionService.find("id not in (select function_id from role2function where role_id=?) ", role_id);
		JSONArray json = JSONArray.fromObject(functions);
		PrintWriter out=response.getWriter();
		logger.debug("queryFunction=" + json.toString());
        out.println(json);
		return null;
	}

	public ActionForward queryFunctionSelected(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		List<Functions> functions = this.functionService.find("id in (select function_id from role2function where role_id=?) ", role_id);
		JSONArray json = JSONArray.fromObject(functions);
		PrintWriter out=response.getWriter();
		logger.debug("queryFunctionSelected=" + json.toString());
        out.println(json);
		return null;
	}

	public ActionForward queryItem(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String role_id = request.getParameter("role_id");
		String function_id = request.getParameter("function_id");
		String sql = "select a.id, a.itemname, a.alias, b.visable, b.enable, a.function_id from functionitems a, ";
		sql += "(select * from role2functionitem where role_id=?) b ";
		sql += "where a.id=b.item_id ";
		List<Map<String, Object>> functionitems = null;
		if (null != function_id) {
			sql += "and a.function_id=? ";
			functionitems = this.commonService.queryForList(sql, role_id, function_id);
		} else {
			sql += "order by a.function_id, a.id ";
			functionitems = this.commonService.queryForList(sql, role_id);
		}
		JSONArray json = JSONArray.fromObject(functionitems);
		PrintWriter out=response.getWriter();
		logger.debug("queryItem=" + json.toString());
        out.println(json);
		return null;
	}

	@Override
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String op = request.getParameter("op");
		Integer userId = (Integer) request.getSession().getAttribute("user_id");
		Roles t = new Roles();
		try {
			// main object
			DynaBean dynaForm = (DynaBean) form;
			PropertyUtils.copyProperties(t, dynaForm.get("vo"));
			// using multiple selectbox
			String[] saAccounts = request.getParameterValues("vo.accounts");
			List<Accounts> listAccounts = new ArrayList<Accounts>();
			if (saAccounts == null) {
				logger.debug("vo.accounts is null");
			} else {
				for (String account_id : saAccounts) {
					Accounts account = new Accounts();
					account.setId(Integer.parseInt(account_id));
					listAccounts.add(account);
				}
			}
			t.setAccounts(listAccounts);
			// using JSON
			String functionJson = request.getParameter("functionJson");
			logger.debug("functionJson=" + functionJson);
			if (!"*".equals(functionJson)) {
				JSONArray jsonArray = JSONArray.fromObject(functionJson);
				if (jsonArray == null) {
					logger.debug("functionJson is null");
				} else {
					logger.debug(jsonArray.toString());
					List<Functions> list = new ArrayList<Functions>();
					List<Role2FunctionItem> itemList = new ArrayList<Role2FunctionItem>();
					for (Iterator<JSONObject> it=jsonArray.iterator(); it.hasNext();) {
						JSONObject jsonObject = it.next();
						Functions function = new Functions();
						function.setId(Integer.parseInt(jsonObject.getString("funcid")));
						list.add(function);
						JSONArray items = jsonObject.getJSONArray("items");
						if (items != null) {
							logger.debug("items=" + items.toString());
							for (Iterator<JSONObject> it1=items.iterator(); it1.hasNext();) {
								JSONObject item = it1.next();
								Role2FunctionItem r2f = new Role2FunctionItem();
								r2f.setRole_id(t.getId());
								r2f.setItem_id(Integer.parseInt(item.getString("id")));
								String visable = item.getString("visable");
								if (visable == null || visable.equals("")) visable = "Y";
								r2f.setVisable(visable);
								String enable = item.getString("enable");
								if (enable == null || enable.equals("")) enable = "Y";
								r2f.setEnable(enable);
								logger.debug(item.getString("id") + "=="
										+ item.getString("visable") + "--" + visable + ";"
										+ item.getString("enable") + "--" + enable );
								itemList.add(r2f);
							}
						}
					}
					t.setFunctions(list);
					t.setRole2functionitem(itemList);
				}
			} else {
				t.setFunctions(null);
				t.setRole2functionitem(null);
			}
		} catch (Exception e) {
			logger.warn("PropertyUtils", e);
			return mapping.findForward("err");
		}
		int ret = -1;
		if ("insert".equals(op)) {
			t.setCreate_by(userId);
			ret = this.baseService.insert(t);
		} else if ("update".equals(op)) {
			t.setUpdate_by(userId);
			ret = this.baseService.update(t);
		} else if ("delete".equals(op)) {
			t.setUpdate_by(userId);
			try{
				ret = this.baseService.delete(t);
			}catch(CdfException cex){
				MessageHandler.getInstance().processError(request, cex.getMessage());
			}
		}
		if (ret > -1) {
			request.setAttribute("entryURL", entryURL);
			return mapping.findForward("success");
		}else {
			return mapping.findForward("err");
		}
	}

}
